package org.jeecg.modules.system.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.constant.CacheConstant;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.constant.enums.ExamineStatusEnum;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.system.util.JwtUtil;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.system.vo.SysUserCacheInfo;
import org.jeecg.common.util.*;
import org.jeecg.modules.base.service.BaseCommonService;
import org.jeecg.modules.system.constant.UserTypeEnum;
import org.jeecg.modules.system.entity.SysDepart;
import org.jeecg.modules.system.entity.SysDepartRole;
import org.jeecg.modules.system.entity.SysDepartRoleUser;
import org.jeecg.modules.system.entity.SysPermission;
import org.jeecg.modules.system.entity.SysRole;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.entity.SysUserDepart;
import org.jeecg.modules.system.entity.SysUserExtend;
import org.jeecg.modules.system.entity.SysUserRole;
import org.jeecg.modules.system.mapper.SysDepartMapper;
import org.jeecg.modules.system.mapper.SysDepartRoleMapper;
import org.jeecg.modules.system.mapper.SysDepartRoleUserMapper;
import org.jeecg.modules.system.mapper.SysPermissionMapper;
import org.jeecg.modules.system.mapper.SysRoleMapper;
import org.jeecg.modules.system.mapper.SysUserDepartMapper;
import org.jeecg.modules.system.mapper.SysUserMapper;
import org.jeecg.modules.system.mapper.SysUserRoleMapper;
import org.jeecg.modules.system.model.SysLoginModel;
import org.jeecg.modules.system.model.SysUserSysDepartModel;
import org.jeecg.modules.system.service.ISysDepartService;
import org.jeecg.modules.system.service.ISysDictService;
import org.jeecg.modules.system.service.ISysUserService;
import org.jeecg.modules.system.vo.SysUserDepVo;
import org.jeecg.modules.wlhy.hydriver.entity.HyDriver;
import org.jeecg.modules.wlhy.hydriver.service.IHyDriverService;
import org.jeecg.modules.wlhy.hyvehicle.entity.HyVehicle;
import org.jeecg.modules.wlhy.hyvehicle.service.IHyDriverVehicleService;
import org.jeecg.modules.wlhy.hyvehicle.service.IHyVehicleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @Author: scott
 * @Date: 2018-12-20
 */
@Service
@Slf4j
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements ISysUserService {

    @Autowired
    private SysUserMapper userMapper;
    @Autowired
    private SysPermissionMapper sysPermissionMapper;
    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;
    @Autowired
    private SysUserDepartMapper sysUserDepartMapper;
    @Autowired
    private ISysBaseAPI sysBaseAPI;
    @Autowired
    private SysDepartMapper sysDepartMapper;
    @Autowired
    private SysRoleMapper sysRoleMapper;
    @Autowired
    private SysDepartRoleUserMapper departRoleUserMapper;
    @Autowired
    private SysDepartRoleMapper sysDepartRoleMapper;
    @Resource
    private BaseCommonService baseCommonService;

    @Autowired
    private ISysDepartService departService;

    @Autowired
    private IHyDriverService hyDriverService;

    @Autowired
    private IHyVehicleService hyVehicleService;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private ISysDictService sysDictService;

    @Autowired
    private IHyDriverVehicleService hyDriverVehicleService;

    @Value(value = "${customer.driver-role-id}")
    private String driverRoleID;
    @Value(value = "${customer.driver-depart-id}")
    private String driverDepartpid;

    @Autowired
    private SysBaseApiImpl sysBaseApiImpl;

    @Override
    @CacheEvict(value = {CacheConstant.SYS_USERS_CACHE}, allEntries = true)
    public Result<?> resetPassword(String username, String oldpassword, String newpassword, String confirmpassword) {
        SysUser user = userMapper.getUserByName(username);
        String passwordEncode = PasswordUtil.encrypt(username, oldpassword, user.getSalt());
        if (!user.getPassword().equals(passwordEncode)) {
            return Result.error("旧密码输入错误!");
        }
        if (oConvertUtils.isEmpty(newpassword)) {
            return Result.error("新密码不允许为空!");
        }
        if (!newpassword.equals(confirmpassword)) {
            return Result.error("两次输入密码不一致!");
        }
        Date dt1 = null;
        if (username.equals("admin")) {
            Date dt = new Date();
            Calendar rightNow = Calendar.getInstance();
            rightNow.setTime(dt);
            rightNow.add(Calendar.MONTH, 3);
            dt1 = rightNow.getTime();
            String password = PasswordUtil.encrypt(username, newpassword, user.getSalt());
            this.userMapper.update(new SysUser().setPassword(password).setOverdueTime(dt1), new LambdaQueryWrapper<SysUser>().eq(SysUser::getId, user.getId()));
            return Result.ok("密码重置成功!");

        }else{
            String password = PasswordUtil.encrypt(username, newpassword, user.getSalt());
            this.userMapper.update(new SysUser().setPassword(password), new LambdaQueryWrapper<SysUser>().eq(SysUser::getId, user.getId()));
            return Result.ok("密码重置成功!");
        }

    }

    @Override
    @CacheEvict(value = {CacheConstant.SYS_USERS_CACHE}, allEntries = true)
    public Result<?> changePassword(SysUser sysUser) {
        String salt = oConvertUtils.randomGen(8);
        sysUser.setSalt(salt);
        String password = sysUser.getPassword();
        String passwordEncode = PasswordUtil.encrypt(sysUser.getUsername(), password, salt);
        sysUser.setPassword(passwordEncode);
        this.userMapper.updateById(sysUser);
        return Result.ok("密码修改成功!");
    }

    @Override
    @CacheEvict(value = {CacheConstant.SYS_USERS_CACHE}, allEntries = true)
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteUser(String userId) {
        //1.删除用户
        this.removeById(userId);
        return false;
    }

    @Override
    @CacheEvict(value = {CacheConstant.SYS_USERS_CACHE}, allEntries = true)
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteBatchUsers(String userIds) {
        //1.删除用户
        this.removeByIds(Arrays.asList(userIds.split(",")));
        return false;
    }

    @Override
    public SysUser getUserByName(String username) {
        return userMapper.getUserByName(username);
    }


    @Override
    @Transactional
    public void addUserWithRole(SysUser user, String roles) {
        this.save(user);
        if (oConvertUtils.isNotEmpty(roles)) {
            String[] arr = roles.split(",");
            for (String roleId : arr) {
                SysUserRole userRole = new SysUserRole(user.getId(), roleId);
                sysUserRoleMapper.insert(userRole);
            }
        }
    }

    @Override
    @CacheEvict(value = {CacheConstant.SYS_USERS_CACHE}, allEntries = true)
    @Transactional
    public void editUserWithRole(SysUser user, String roles) {
        this.updateById(user);
        //先删后加
        sysUserRoleMapper.delete(new QueryWrapper<SysUserRole>().lambda().eq(SysUserRole::getUserId, user.getId()));
        if (oConvertUtils.isNotEmpty(roles)) {
            String[] arr = roles.split(",");
            for (String roleId : arr) {
                SysUserRole userRole = new SysUserRole(user.getId(), roleId);
                sysUserRoleMapper.insert(userRole);
            }
        }
    }


    @Override
    public List<String> getRole(String username) {
        return sysUserRoleMapper.getRoleByUserName(username);
    }

    /**
     * 通过用户名获取用户角色集合
     *
     * @param username 用户名
     * @return 角色集合
     */
    @Override
    public Set<String> getUserRolesSet(String username) {
        // 查询用户拥有的角色集合
        List<String> roles = sysUserRoleMapper.getRoleByUserName(username);
//        log.info("-------通过数据库读取用户拥有的角色Rules------username： " + username + ",Roles size: " + (roles == null ? 0 : roles.size()));
        return new HashSet<>(roles);
    }

    /**
     * 通过用户名获取用户权限集合
     *
     * @param username 用户名
     * @return 权限集合
     */
    @Override
    public Set<String> getUserPermissionsSet(String username) {
        Set<String> permissionSet = new HashSet<>();
        List<SysPermission> permissionList = sysPermissionMapper.queryByUser(username);
        for (SysPermission po : permissionList) {
//			// TODO URL规则有问题？
//			if (oConvertUtils.isNotEmpty(po.getUrl())) {
//				permissionSet.add(po.getUrl());
//			}
            if (oConvertUtils.isNotEmpty(po.getPerms())) {
                permissionSet.add(po.getPerms());
            }
        }
//        log.info("-------通过数据库读取用户拥有的权限Perms------username： " + username + ",Perms size: " + (permissionSet == null ? 0 : permissionSet.size()));
        return permissionSet;
    }

    @Override
    public SysUserCacheInfo getCacheUser(String username) {
        SysUserCacheInfo info = new SysUserCacheInfo();
        info.setOneDepart(true);
//		SysUser user = userMapper.getUserByName(username);
//		info.setSysUserCode(user.getUsername());
//		info.setSysUserName(user.getRealname());


        LoginUser user = sysBaseAPI.getUserByName(username);
        if (user != null) {
            info.setSysUserCode(user.getUsername());
            info.setSysUserName(user.getRealname());
            info.setSysOrgCode(user.getOrgCode());
        }

        //多部门支持in查询
        List<SysDepart> list = sysDepartMapper.queryUserDeparts(user.getId());
        List<String> sysMultiOrgCode = new ArrayList<String>();
        if (list == null || list.size() == 0) {
            //当前用户无部门
            //sysMultiOrgCode.add("0");
        } else if (list.size() == 1) {
            sysMultiOrgCode.add(list.get(0).getOrgCode());
        } else {
            info.setOneDepart(false);
            for (SysDepart dpt : list) {
                sysMultiOrgCode.add(dpt.getOrgCode());
            }
        }
        info.setSysMultiOrgCode(sysMultiOrgCode);

        return info;
    }

    // 根据部门Id查询
    @Override
    public IPage<SysUser> getUserByDepId(Page<SysUser> page, String departId, String username) {
        return userMapper.getUserByDepId(page, departId, username);
    }



    @Override
    public IPage<SysUser> getUserByDepIds(Page<SysUser> page, List<String> departIds, String username) {
        return userMapper.getUserByDepIds(page, departIds, username);
    }

    @Override
    public Map<String, String> getDepNamesByUserIds(List<String> userIds) {
        List<SysUserDepVo> list = this.baseMapper.getDepNamesByUserIds(userIds);

        Map<String, String> res = new HashMap<String, String>();
        list.forEach(item -> {
                    if (res.get(item.getUserId()) == null) {
                        res.put(item.getUserId(), item.getDepartName());
                    } else {
                        res.put(item.getUserId(), res.get(item.getUserId()) + "," + item.getDepartName());
                    }
                }
        );
        return res;
    }

    @Override
    public IPage<SysUser> getUserByDepartIdAndQueryWrapper(Page<SysUser> page, String departId, QueryWrapper<SysUser> queryWrapper) {
        LambdaQueryWrapper<SysUser> lambdaQueryWrapper = queryWrapper.lambda();

        lambdaQueryWrapper.eq(SysUser::getDelFlag, CommonConstant.DEL_FLAG_0);
        lambdaQueryWrapper.inSql(SysUser::getId, "SELECT user_id FROM sys_user_depart WHERE dep_id = '" + departId + "'");

        return userMapper.selectPage(page, lambdaQueryWrapper);
    }

    @Override
    public IPage<SysUserSysDepartModel> queryUserByOrgCode(String orgCode, SysUser userParams, IPage page) {
        List<SysUserSysDepartModel> list = baseMapper.getUserByOrgCode(page, orgCode, userParams);
        Integer total = baseMapper.getUserByOrgCodeTotal(orgCode, userParams);

        IPage<SysUserSysDepartModel> result = new Page<>(page.getCurrent(), page.getSize(), total);
        result.setRecords(list);

        return result;
    }

    // 根据角色Id查询
    @Override
    public IPage<SysUser> getUserByRoleId(Page<SysUser> page, String roleId, String username) {
        return userMapper.getUserByRoleId(page, roleId, username);
    }

    @Override
    public IPage<SysUser> getUserByRoleId(Page<SysUser> page, String roleId, String realname ,String phone) {
        return userMapper.getUserByRoleId1(page, roleId, realname ,phone);
    }




    @Override
    @CacheEvict(value = {CacheConstant.SYS_USERS_CACHE}, key = "#username")
    public void updateUserDepart(String username, String orgCode) {
        baseMapper.updateUserDepart(username, orgCode);
    }


    @Override
    public SysUser getUserByPhone(String phone) {
        return userMapper.getUserByPhone(phone);
    }


    @Override
    public SysUser getUserByEmail(String email) {
        return userMapper.getUserByEmail(email);
    }

    @Override
    @Transactional
    public void addUserWithDepart(SysUser user, String selectedParts) {
//		this.save(user);  //保存角色的时候已经添加过一次了
        if (oConvertUtils.isNotEmpty(selectedParts)) {
            String[] arr = selectedParts.split(",");
            for (String deaprtId : arr) {
                SysUserDepart userDeaprt = new SysUserDepart(user.getId(), deaprtId);
                sysUserDepartMapper.insert(userDeaprt);
            }
        }
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(value = {CacheConstant.SYS_USERS_CACHE}, allEntries = true)
    public void editUserWithDepart(SysUser user, String departs) {
        this.updateById(user);  //更新角色的时候已经更新了一次了，可以再跟新一次
        String[] arr = {};
        if (oConvertUtils.isNotEmpty(departs)) {
            arr = departs.split(",");
        }
        //查询已关联部门
        List<SysUserDepart> userDepartList = sysUserDepartMapper.selectList(new QueryWrapper<SysUserDepart>().lambda().eq(SysUserDepart::getUserId, user.getId()));
        if (userDepartList != null && userDepartList.size() > 0) {
            for (SysUserDepart depart : userDepartList) {
                //修改已关联部门删除部门用户角色关系
                if (!Arrays.asList(arr).contains(depart.getDepId())) {
                    List<SysDepartRole> sysDepartRoleList = sysDepartRoleMapper.selectList(
                            new QueryWrapper<SysDepartRole>().lambda().eq(SysDepartRole::getDepartId, depart.getDepId()));
                    List<String> roleIds = sysDepartRoleList.stream().map(SysDepartRole::getId).collect(Collectors.toList());
                    if (roleIds != null && roleIds.size() > 0) {
                        departRoleUserMapper.delete(new QueryWrapper<SysDepartRoleUser>().lambda().eq(SysDepartRoleUser::getUserId, user.getId())
                                .in(SysDepartRoleUser::getDroleId, roleIds));
                    }
                }
            }
        }
        //先删后加
        sysUserDepartMapper.delete(new QueryWrapper<SysUserDepart>().lambda().eq(SysUserDepart::getUserId, user.getId()));
        if (oConvertUtils.isNotEmpty(departs)) {
            for (String departId : arr) {
                SysUserDepart userDepart = new SysUserDepart(user.getId(), departId);
                sysUserDepartMapper.insert(userDepart);
            }
        }
    }


    /**
     * 校验用户是否有效
     *
     * @param sysUser
     * @return
     */
    @Override
    public Result<?> checkUserIsEffective(SysUser sysUser) {
        Result<?> result = new Result<Object>();
        //情况1：根据用户信息查询，该用户不存在
        if (sysUser == null) {
            result.error500("用户不存在或密码错误");
            baseCommonService.addLog("用户登录失败，用户不存在！", CommonConstant.LOG_TYPE_1, null);
            return result;
        }
        //情况2：根据用户信息查询，该用户已注销
        //update-begin---author:王帅   Date:20200601  for：if条件永远为falsebug------------
        if (CommonConstant.DEL_FLAG_1.equals(sysUser.getDelFlag())) {
            //update-end---author:王帅   Date:20200601  for：if条件永远为falsebug------------
            baseCommonService.addLog("用户登录失败，用户名:" + sysUser.getUsername() + "已注销！", CommonConstant.LOG_TYPE_1, null);
            result.error500("该用户已注销");
            return result;
        }
        //情况3：根据用户信息查询，该用户已冻结
        if (CommonConstant.USER_FREEZE.equals(sysUser.getStatus())) {
            baseCommonService.addLog("用户登录失败，用户名:" + sysUser.getUsername() + "已冻结！", CommonConstant.LOG_TYPE_1, null);
            result.error500("该用户已冻结");
            return result;
        }
        return result;
    }

    @Override
    public List<SysUser> queryLogicDeleted() {
        return this.queryLogicDeleted(null);
    }

    @Override
    public List<SysUser> queryLogicDeleted(LambdaQueryWrapper<SysUser> wrapper) {
        if (wrapper == null) {
            wrapper = new LambdaQueryWrapper<>();
        }
        wrapper.eq(SysUser::getDelFlag, CommonConstant.DEL_FLAG_1);
        return userMapper.selectLogicDeleted(wrapper);
    }

    @Override
    public boolean revertLogicDeleted(List<String> userIds, SysUser updateEntity) {
        String ids = String.format("'%s'", String.join("','", userIds));
        return userMapper.revertLogicDeleted(ids, updateEntity) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean removeLogicDeleted(List<String> userIds) {
        String ids = String.format("'%s'", String.join("','", userIds));
        // 1. 删除用户
        int line = userMapper.deleteLogicDeleted(ids);
        // 2. 删除用户部门关系
        line += sysUserDepartMapper.delete(new LambdaQueryWrapper<SysUserDepart>().in(SysUserDepart::getUserId, userIds));
        //3. 删除用户角色关系
        line += sysUserRoleMapper.delete(new LambdaQueryWrapper<SysUserRole>().in(SysUserRole::getUserId, userIds));
        return line != 0;
    }

    /**
     * 彻底删除用户 慎用
     * @param userIds
     * @return
     */
    @Override
    public boolean deleteUser(List<String> userIds) {
        String ids = String.format("'%s'", String.join("','", userIds));
        // 1. 删除用户
        int line = userMapper.deleteUser(ids);
        // 2. 删除用户部门关系
        line += sysUserDepartMapper.delete(new LambdaQueryWrapper<SysUserDepart>().in(SysUserDepart::getUserId, userIds));
        //3. 删除用户角色关系
        line += sysUserRoleMapper.delete(new LambdaQueryWrapper<SysUserRole>().in(SysUserRole::getUserId, userIds));
        return line != 0;
    }

    @Override
    public SysUser getUserByPhoneNew(String phone) {
        return userMapper.getUserByPhoneNew(phone);
    }



    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateNullPhoneEmail() {
        userMapper.updateNullByEmptyString("email");
        userMapper.updateNullByEmptyString("phone");
        return true;
    }

    @Override
    public void saveThirdUser(SysUser sysUser) {
        //保存用户
        String userid = UUIDGenerator.generate();
        sysUser.setId(userid);
        baseMapper.insert(sysUser);
        //获取第三方角色
        SysRole sysRole = sysRoleMapper.selectOne(new LambdaQueryWrapper<SysRole>().eq(SysRole::getRoleCode, "third_role"));
        //保存用户角色
        SysUserRole userRole = new SysUserRole();
        userRole.setRoleId(sysRole.getId());
        userRole.setUserId(userid);
        sysUserRoleMapper.insert(userRole);
    }

    @Override
    public List<SysUser> queryByDepIds(List<String> departIds, String username) {
        return userMapper.queryByDepIds(departIds, username);
    }

    /**
     * 用户信息
     *
     * @param sysUser
     * @param result
     * @return
     */
    @Override
    public Result<JSONObject> userInfo(SysUser sysUser, Result<JSONObject> result) {
        String syspassword = sysUser.getPassword();
        String username = sysUser.getUsername();
        // 生成token
        String token = JwtUtil.sign(username, syspassword);
        String uType = sysUser.getUType();
        //网页端用户， 设置token缓存有效时间
        if (UserTypeEnum.管理员.getCode().equals(uType) || UserTypeEnum.业务管理员.getCode().equals(uType)) {
            redisUtil.set(CommonConstant.PREFIX_USER_TOKEN + token, token, 60 * 30);
        } else if (UserTypeEnum.货主.getCode().equals(uType) || UserTypeEnum.货主子账号.getCode().equals(uType)||UserTypeEnum.承运商.getCode().equals(uType)) {
            redisUtil.set(CommonConstant.PREFIX_USER_TOKEN + token, token, 60 * 60 * 12);
        }

        // 获取用户部门信息
        JSONObject obj = new JSONObject();
        List<SysDepart> departs = sysDepartMapper.queryUserDeparts(sysUser.getId());
        obj.put("departs", departs);
        if (departs == null || departs.size() == 0) {
            obj.put("multi_depart", 0);
        } else if (departs.size() == 1) {
            baseMapper.updateUserDepart(username, departs.get(0).getOrgCode());
            obj.put("multi_depart", 1);
        } else {
            //查询当前是否有登录部门
            // update-begin--Author:wangshuai Date:20200805 for：如果用戶为选择部门，数据库为存在上一次登录部门，则取一条存进去
            SysUser sysUserById = this.getById(sysUser.getId());
            if (oConvertUtils.isEmpty(sysUserById.getOrgCode())) {
                baseMapper.updateUserDepart(username, departs.get(0).getOrgCode());
            }
            // update-end--Author:wangshuai Date:20200805 for：如果用戶为选择部门，数据库为存在上一次登录部门，则取一条存进去
            obj.put("multi_depart", 2);
        }
        obj.put("token", token);
        obj.put("userInfo", sysUser);
        obj.put("sysAllDictItems", sysDictService.queryAllDictItems());
        result.setResult(obj);
        result.success("登录成功");
        return result;
    }

    /**
     * 司机用户信息
     *
     * @param sysUser
     * @param result
     * @return
     */
    @Override
    public Result<JSONObject> appUserInfo(SysUser sysUser, Result<JSONObject> result) {

        String syspassword = sysUser.getPassword();
        String username = sysUser.getUsername();
        sysBaseApiImpl.getUserByName(username);
        // 生成token
        String token = JwtUtil.sign(username, syspassword);
        // 设置token缓存有效时间
        redisUtil.set(CommonConstant.PREFIX_USER_TOKEN + token, token);
        redisUtil.expire(CommonConstant.PREFIX_USER_TOKEN + token, 86400000 * 7 / 1000);

        SysUserExtend userExtend =  this.getRefreshDriverUserInfo( sysUser, result) ;

        // 获取用户部门信息
        JSONObject obj = new JSONObject();
        obj.put("sysAllDictItems", sysDictService.queryAllDictItems());
        obj.put("token", token);
        obj.put("userInfo", userExtend);
        result.setResult(obj);
        return result;
    }

    @Override
    public SysUserExtend getRefreshDriverUserInfo(SysUser sysUser, Result<JSONObject> result) {
        SysUserExtend userExtend = SysUserTOSysUserExtend(sysUser);

        //获取司机信息和车辆信息的审核状态
        userExtend.setDriverCertifiedStatus(0);
        userExtend.setVehicleCertifiedStatus(0);
        HyDriver hyDriver = hyDriverService.getHyDriverByUserId(sysUser.getId());
        if (hyDriver != null) {
            userExtend.setDriverCertifiedStatus(
                    hyDriver.getExamineStatus() != null ?
                            Integer.valueOf(hyDriver.getExamineStatus()) : 0
            );
            userExtend.setDriverExaminRemark(StringUtils.isNotEmpty(hyDriver.getExaminRemark()) ?
                    hyDriver.getExaminRemark() : StringUtils.EMPTY
            );
            List<String> vehicleIds = hyDriverVehicleService.getVehicleIdListByDriverId(hyDriver.getId());
            List<HyVehicle> hyVehicles = null;
            if (CollectionUtils.isNotEmpty(vehicleIds)) {
                QueryWrapper<HyVehicle> queryVehicleWrapper = new QueryWrapper();
                queryVehicleWrapper.in("id", vehicleIds);
                queryVehicleWrapper.orderByDesc("examine_status");
                hyVehicles = hyVehicleService.list(queryVehicleWrapper);
            }

            boolean isVehicleStatus = false;
            String examinRemark = StringUtils.EMPTY;
            if (CollectionUtils.isNotEmpty(hyVehicles)) {
                for (HyVehicle hyVehicle : hyVehicles) {
                    if (hyVehicle.getExamineStatus().equals(ExamineStatusEnum.EXAMINE_STATUS_TOREVIEWED.getCode())) {
                        examinRemark = examinRemark + hyVehicle.getVehicleNumber() + " " + ExamineStatusEnum.EXAMINE_STATUS_TOREVIEWED.getMsg() + "; ";
                    }
                    if (hyVehicle.getExamineStatus().equals(ExamineStatusEnum.EXAMINE_STATUS_AUDIT_FAILURE.getCode())) {
                        examinRemark = examinRemark + hyVehicle.getVehicleNumber() + " " + ExamineStatusEnum.EXAMINE_STATUS_AUDIT_FAILURE.getMsg() + ":" + hyVehicle.getExaminRemark() + "; ";
                    }
                    if (hyVehicle.getExamineStatus().equals(ExamineStatusEnum.EXAMINE_STATUS_APPROVED.getCode())) {
                        isVehicleStatus = true;
                        break;
                    }
                }
            }
            userExtend.setVehicleExaminRemark(
                    isVehicleStatus ? StringUtils.EMPTY :
                            StringUtils.isNotEmpty(examinRemark) ? examinRemark : "您还未添加车辆信息，请您先添加车辆信息！"
            );
            userExtend.setVehicleCertifiedStatus(isVehicleStatus ? 2 : 1);
        }

        return userExtend;
    }

    private static SysUserExtend SysUserTOSysUserExtend(SysUser user) {
        if (user == null) {
            return null;
        }
        SysUserExtend sysUserExtend = new SysUserExtend();
        sysUserExtend.setId(user.getId());
        sysUserExtend.setUsername(user.getUsername());
        sysUserExtend.setRealname(user.getRealname());
        sysUserExtend.setPassword(user.getPassword());
        sysUserExtend.setSalt(user.getSalt());
        sysUserExtend.setAvatar(user.getAvatar());
        sysUserExtend.setBirthday(user.getBirthday());
        sysUserExtend.setSex(user.getSex());
        sysUserExtend.setEmail(user.getEmail());
        sysUserExtend.setPhone(user.getPhone());
        sysUserExtend.setOrgCode(user.getOrgCode());
        sysUserExtend.setOrgCodeTxt(user.getOrgCodeTxt());
        sysUserExtend.setStatus(user.getStatus());
        sysUserExtend.setDelFlag(user.getDelFlag());
        sysUserExtend.setWorkNo(user.getWorkNo());
        sysUserExtend.setPost(user.getPost());
        sysUserExtend.setTelephone(user.getTelephone());
        sysUserExtend.setCreateBy(user.getCreateBy());
        sysUserExtend.setCreateTime(user.getCreateTime());
        sysUserExtend.setUpdateBy(user.getUpdateBy());
        sysUserExtend.setUpdateTime(user.getUpdateTime());
        sysUserExtend.setActivitiSync(user.getActivitiSync());
        sysUserExtend.setUserIdentity(user.getUserIdentity());
        sysUserExtend.setDepartIds(user.getDepartIds());
        sysUserExtend.setThirdId(user.getThirdId());
        sysUserExtend.setThirdType(user.getThirdType());
        sysUserExtend.setRelTenantIds(user.getRelTenantIds());
        sysUserExtend.setClientId(user.getClientId());
        return sysUserExtend;
    }

    /**
     * 司机注册
     *
     * @param sysLoginModel
     * @return
     */
    @Override
    public Result<JSONObject> registerDriver(SysLoginModel sysLoginModel, HttpServletResponse response) {
        Result<JSONObject> result = new Result<JSONObject>();
        try {
            SysDepart sysDepart = departService.getSysDepartById(driverDepartpid);
            String phone = sysLoginModel.getPhone();
            SysUser user = new SysUser();
            user.setCreateTime(new Date());

            String username = this.createRandomUserName();//随机生成账号
            user.setUsername(username);
           // user.setUsername(phone);
            String salt = oConvertUtils.randomGen(8);
            user.setSalt(salt);
            //密码为空补充密码
            user.setPassword(sysLoginModel.getPassword());
            if (StringUtils.isBlank(sysLoginModel.getPassword())) {
                //设置默认密码123456
                user.setPassword("Aa.123456");
            }
            String passwordEncode = PasswordUtil.encrypt(user.getUsername(), user.getPassword(), salt);
            user.setPassword(passwordEncode);
            user.setRealname(phone);
            user.setPhone(phone);
            user.setActivitiSync(CommonConstant.ACT_SYNC_0);
            user.setOrgCode(sysDepart.getOrgCode());
            user.setStatus(CommonConstant.USER_UNFREEZE);
            user.setDelFlag(CommonConstant.DEL_FLAG_0);
            user.setCreateBy(user.getUsername());
            user.setUType("4");
            user.setClientId(sysLoginModel.getClientId());
            addUserWithRole(user, driverRoleID);
            addUserWithDepart(user, sysDepart.getId());
            appUserInfo(user, result);
            setUserCookie(user.getUsername(), response);
            result.success("司机注册成功");
        } catch (Exception e) {
            result.error500("司机已注册,请勿重复注册,请登录！");
        }
        return result;
    }

    @Override
    public void setUserCookie(String username, HttpServletResponse response) {
        Cookie cookie= new Cookie(CommonConstant.X_PC_COOKIE, MD5Util.MD5Encode(username, "utf-8"));
        cookie.setPath("/");
        cookie.setMaxAge(60 * 60 * 24 * 30);
        cookie.setHttpOnly(true);
        ((HttpServletResponse)response).addCookie(cookie);
        log.info("APP登录设置cookie - CMAP_SECKEY - {}", cookie.getValue());

        return;
    }

    @Override
    public List<SysUserRole> getUserRoles(String userId) {
        List<SysUserRole> list = sysUserRoleMapper.selectList(new QueryWrapper<SysUserRole>().eq("user_id", userId));
        return list;
    }

    @Override
    public String createRandomUserName() {
        for (int i = 0; i < 10; i++) {
            String username = oConvertUtils.randomGen(16);
            int count = this.count(new QueryWrapper<SysUser>().eq("username", username));
            if (count == 0) {
                return username;
            }
        }
        throw new JeecgBootException("生成用户失败");
    }

}
